package developer.算法.二叉树.验证二叉搜索树;

/**
 * @author zhangyongkang
 * @time 2025/3/25 14:03
 * @description 给你一个二叉树的根节点 root ，判断其是否是一个有效的二叉搜索树。
 * <p>
 * 有效 二叉搜索树定义如下：
 * <p>
 * 节点的左子树只包含 小于 当前节点的数。
 * 节点的右子树只包含 大于 当前节点的数。
 * 所有左子树和右子树自身必须也是二叉搜索树。
 * <p>
 * <p>
 * 输入：root = [2,1,3]
 * 输出：true
 * <p>
 * 输入：root = [5,1,4,null,null,3,6]
 * 输出：false
 * 解释：根节点的值是 5 ，但是右子节点的值是 4 。
 */
public class YanZhengErChaSouSuoShu {

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    public static void main(String[] args) {
        Solution solution = new Solution();
        TreeNode root = new TreeNode(2, new TreeNode(1), new TreeNode(3));
        TreeNode root2 = new TreeNode(1, new TreeNode(1), new TreeNode());

        System.out.println(solution.isValidBST(root2));
        System.out.println(Integer.MAX_VALUE > 2147483647);
    }

    static class Solution {

        public boolean isValidBST(TreeNode root) {
            return isValidBSTHandle(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
        }

        public boolean isValidBSTHandle(TreeNode root, int low, int high) {
            if (root == null) return true;
            if (root.val >= high || root.val <= low) return false;
            return isValidBSTHandle(root.left, low, root.val) && isValidBSTHandle(root.right, root.val, high);
        }
    }

    static class SolutionOfficial {
        public boolean isValidBST(TreeNode root) {
            return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
        }

        public boolean isValidBST(TreeNode node, long lower, long upper) {
            if (node == null) {
                return true;
            }
            if (node.val <= lower || node.val >= upper) {
                return false;
            }
            //左侧节点的所有值不能大于当前节点
            //右侧节点的所有值不能小于当前节点
            return isValidBST(node.left, lower, node.val) && isValidBST(node.right, node.val, upper);
        }
    }


    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
